#include "ADC_voltage.h"

void ADC_Volt_Init(void)
{

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_ADC1,ENABLE);
    GPIO_InitTypeDef GPIO_InitStuctne;
    ADC_InitTypeDef ADC_InitStuctue;

    GPIO_InitStuctne.GPIO_Mode = GPIO_Mode_AIN;  /*io口配置为模拟输出*/
    GPIO_InitStuctne.GPIO_Pin = GPIO_Pin_1;      
    GPIO_InitStuctne.GPIO_Speed = GPIO_Speed_10MHz;
    GPIO_Init(GPIOA,&GPIO_InitStuctne);

    RCC_ADCCLKConfig(RCC_PCLK2_Div6);                /*ADC时钟设置   Div6 —> 6分频*/
    ADC_DeInit(ADC1);
    ADC_InitStuctue.ADC_Mode = ADC_Mode_Independent;                  /*ADC模式选择：单独工作*/
    ADC_InitStuctue.ADC_ScanConvMode = DISABLE;                       /*ADC单通道采样*/
    ADC_InitStuctue.ADC_ContinuousConvMode = DISABLE;                 /*ADC单次采样*/
    ADC_InitStuctue.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; /*软件触发ADC*/
    ADC_InitStuctue.ADC_DataAlign = ADC_DataAlign_Right;              /*数据右对齐*/
    ADC_InitStuctue.ADC_NbrOfChannel = 1;                             /*ADC转换数目*/
    ADC_Init(ADC1,&ADC_InitStuctue);                                  /*ADC初始化*/

     
    ADC_Cmd(ADC1,ENABLE);        /*开启ADC*/     
    ADC_ResetCalibration(ADC1);                  /*重置ADC校准器*/
    while (ADC_GetResetCalibrationStatus(ADC1)); /*等待校准完成*/

    ADC_StartCalibration(ADC1);             /*开始校准*/
    while (ADC_GetCalibrationStatus(ADC1)); /*等待校准完成*/

}

/*单次ADC取值*/
uint16_t ADC_Get()  
{
    ADC_RegularChannelConfig(ADC1,ADC_Channel_1,1,ADC_SampleTime_239Cycles5);/*通道设置*/
    ADC_SoftwareStartConvCmd(ADC1,ENABLE);  /*软起动ADC*/

    while (!ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC));  /*检查ADC标志位是否置1*/
    return ADC_GetConversionValue(ADC1);            /*返回ADC值*/

}

/*取time次ADC值求平均值返回*/
uint16_t Get_ADC_Data(uint8_t time)
{
    uint32_t data;
    
    for (uint8_t k = 0; k < time; k++)
    {
        data += ADC_Get();
        Delay_ms(5);
    }
    return data/time;
}
